<template>
  <div class="echart-universal-container" :style="containerStyle">
    <v-chart ref="chartRef" :option="option" :theme="theme" :style="chartStyle" autoresize />
  </div>
</template>

<script setup lang="ts">
import { onMounted, computed, ref } from 'vue';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, LineChart, PieChart, GaugeChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components';
import 'echarts-liquidfill';

// 注册ECharts组件
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  GaugeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
]);

// Props定义
interface Props {
  option?: any;
  width?: string;
  height?: string;
  theme?: string;
  loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  option: () => ({
    title: { text: '示例图表', left: 'center' },
    xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] },
    yAxis: { type: 'value' },
    series: [{ data: [120, 200, 150, 80, 70], type: 'bar' }]
  }),
  width: '100%',
  height: '400px',
  theme: 'default',
  loading: false
});

// 图表引用
const chartRef = ref<InstanceType<typeof VChart>>();

// 容器样式 - 确保自适应
const containerStyle = computed(() => ({
  width: '100%',
  height: '100%',
  minHeight: '300px'
}));

// 图表样式 - 确保图表填满容器
const chartStyle = computed(() => ({
  width: '100%',
  height: '100%'
}));

onMounted(() => {
  // ECharts通用组件已挂载，确保图表可以正确响应尺寸变化
  if (chartRef.value) {
    // 延迟调用resize确保图表正确渲染
    setTimeout(() => {
      chartRef.value?.resize();
    }, 100);
  }
});
</script>

<style scoped>
.echart-universal-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;
  overflow: hidden;
}

/* 确保图表能够正确响应容器大小变化 */
.echart-universal-container > div {
  width: 100% !important;
  height: 100% !important;
}
</style>
